/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.wxpay.config.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.entity.OrderEntity;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.PayOrderForm;
import io.renren.modules.app.form.SearchOrderStatusForm;
import io.renren.modules.app.service.OrderService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/app/wx")
public class WXController {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;

    @Login
    @PostMapping("/nativePayOrder")
    @ApiOperation("native付款")
    public R nativePayOrder(@RequestBody PayOrderForm form, @RequestHeader HashMap header) {
        ValidatorUtils.validateEntity(form);
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = form.getOrderId();
        UserEntity user = new UserEntity();
        user.setUserId(userId);
        QueryWrapper wrapper = new QueryWrapper(user);
        long count = userService.count(wrapper);
        if (count == 0) {
            return R.error("用户不存在");
        }
        OrderEntity order = new OrderEntity();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        wrapper = new QueryWrapper(order);
        count = orderService.count(wrapper);
        if (count == 0) {
            return R.error("无效订单");
        }
        order = new OrderEntity();
        order.setId(orderId);
        wrapper = new QueryWrapper(order);
        order = orderService.getOne(wrapper);
        //向微信平台发出请求，创建支付订单
        String amount = order.getAmount().multiply(new BigDecimal("100")).intValue() + "";
        try {
            String code = UUID.randomUUID().toString().replace("-", "");
            Map map = new HashMap();
            map.put("appid", "wxab8acb865bb1637e");
            map.put("mch_id", "11473623");
            map.put("body", "购买一个商品");
            map.put("out_trade_no", code);
            map.put("total_fee", "1");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "127.0.0.1");
            map.put("trade_type", "NATIVE");
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            String xmlParam = WXPayUtil.generateSignedXml(map, "2ab9071b06b9f739b950ddb41db2690d");
            HttpClient httpclient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpclient.isHttps();
            httpclient.setXmlParam(xmlParam);
            httpclient.post();
            String result = httpclient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            if (resultMap.get("prepay_id") != null) {
                order.setPrepayId(resultMap.get("prepay_id"));
                order.setCode(code);
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", order.getId());
                orderService.update(order, updateWrapper);
                return R.ok().put("codeUrl", resultMap.get("code_url"));
            } else {
                return R.error("订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("微信支付模块故障");
        }
    }

    @GetMapping("/qrcode")
    public void qrcode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String codeUrl = request.getParameter("codeUrl");
        if (codeUrl != null && codeUrl.length() > 0) {
            QrConfig qrConfig = new QrConfig();
            qrConfig.setWidth(250);
            qrConfig.setHeight(250);
            qrConfig.setMargin(2);
            OutputStream out = response.getOutputStream();
            QrCodeUtil.generate(codeUrl, qrConfig, "jpg", out);
            out.close();
        }
    }

    @Login
    @PostMapping("/searchOrderStatus")
    @ApiOperation("查询支付订单状态")
    public R searchOrderStatus(@RequestBody SearchOrderStatusForm form, @RequestHeader HashMap header) {
        ValidatorUtils.validateEntity(form);
        String token = header.get("token").toString();
        int userId = Integer.parseInt(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = form.getOrderId();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userId);
        orderEntity.setId(orderId);
        QueryWrapper wrapper = new QueryWrapper(orderEntity);
        int count = orderService.count(wrapper);
        if (count == 0) {
            return R.error("用户与订单不匹配");
        }
        orderEntity = orderService.getOne(wrapper);
        String code = orderEntity.getCode();
        try {
            HashMap map = new HashMap();
            map.put("appid", "wxab8acb865bb1637e");
            map.put("mch_id", "11473623");
            map.put("out_trade_no",code);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            String xmlParam = WXPayUtil.generateSignedXml(map, "2ab9071b06b9f739b950ddb41db2690d");
            HttpClient httpclient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpclient.isHttps();
            httpclient.setXmlParam(xmlParam);
            httpclient.post();
            String result = httpclient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            String returnCode = resultMap.get("return_code");
            String resultCode = resultMap.get("result_code");
            System.out.println(resultMap + "------");
            if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                String tradeState = resultMap.get("trade_state");
                if ("SUCCESS".equals(tradeState)){
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("code",code);
                    updateWrapper.set("status",2);
                    updateWrapper.set("payment_type",1);
                    orderService.update(updateWrapper);
                    return R.ok("订单状态已修改");
                }else {
                    return R.ok("订单状态未修改");
                }
            }
            return R.ok("订单状态未修改");
        }catch (Exception e){
            e.printStackTrace();
            return R.error("查询支付订单失败");
        }
    }
}

